<template>
  <uni-popup ref="validDialog" :is-mask-click="false" type="dialog">
    <view class="valid-dialog">
      <view class="valid-dialog__body">
        <view
          @click="getCaptcha"
          class="captcha-image flex flex-row justify-center align-center"
          :style="{backgroundImage: `url(${captchaData?.image})`}" >
          <view v-if="!captchaData?.image">图片加载失败，请点击重新加载</view>
        </view>
        <view class="valid-dialog-form">
          <uni-forms ref="formRef" :modelValue="form" :rules="rules">
            <uni-forms-item name="validValue">
              <uni-easyinput
                class="login-input mt2"
                prefixIcon="auth"
                :clearable="false"
                v-model="form.validValue"
                placeholder="请输入验证码"
              />
            </uni-forms-item>
          </uni-forms>
        </view>
      </view>
      <view class="dialog-footer flex flex-row">
        <d-button class="flex-grow-1 close-btn" @click="close" type="info" text>取消</d-button>
        <d-button class="flex-grow-1" @click="confirm" text>确认</d-button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import {useLoginApi} from "@/api/login";
import {ICaptcha, LoginBaseData} from "@/types/login";

defineOptions({ name: 'LoginValidDialog' })

const $emit = defineEmits(['confirm'])

const form = reactive({
  validValue: null
});

const rules = {
  validValue: { rules: [{required: true, errorMessage: '域名项必填'}]}
}

const validDialog = ref();
const captchaData = ref<ICaptcha>();
function open(data: LoginBaseData) {
  console.log(data)
  getCaptcha(data).then(() => {
    validDialog.value.open()
  })
}

function getCaptcha(data: LoginBaseData): Promise<ICaptcha> {
  return new Promise<ICaptcha>((resolve, reject) => {
    useLoginApi().getCaptcha({
      state: data.state,
      captcha: data.captcha,
    }).then(res => {
      if (res.data) {
        captchaData.value = res.data as ICaptcha
        resolve(res.data)
      }
    }).catch(() => {
      reject();
    })
  })
}

const formRef = ref();
function confirm() {
  formRef.value.validate().then(() => {
    validDialog.value.close()
    $emit('confirm', form.validValue)
  })
}

function close() {
  validDialog.value.close()
}

defineExpose({
  open,
  close,
  validValue: form.validValue,
})
</script>

<style scoped lang="scss">
.valid-dialog {
  margin: 0 auto;
  width: 80vw;
  background-color: #fff;
  border-radius: 16rpx;

  &__body {

    .valid-dialog-form {
      padding: 0 20rpx;
    }

    .captcha-image {
      width: 100%;
      aspect-ratio: 3/1;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
    }
  }
}

.dialog-footer {
  border-top: 1px solid rgba(0, 0, 0, 0.1)
}

.close-btn {
  border-right: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: unset;
}
</style>
